package top.lyjwn.ajui.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.view.View;
import android.view.ViewOutlineProvider;

/**
 * @author luoyujuie
 * 视图圆角处理
 */
public class RoundUtil {

    /**
     * 默认圆角处理
     *
     * @param view
     */
    public static void clipViewCircle(View view) {
        view.setClipToOutline(true);
        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, view.getWidth(), view.getHeight());
            }
        });
    }

    /**
     * @param view
     * @param pixel 可填半径的圆角处理
     */
    public static void clipViewCornerByDp(View view, int pixel) {
        view.setClipToOutline(true);
        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), pixel);
            }
        });
    }

    /**
     * 可填半径的圆角处理
     *
     * @param view
     * @param width
     * @param height
     * @param pixel
     */
    public static void clipViewCornerByDp(View view, final int width, final int height, final int pixel) {

        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, width, height, pixel);
            }
        });
        view.setClipToOutline(true);
    }

    /**
     * 图片圆形剪切
     *
     * @param source
     * @return
     */
    public static Bitmap cutRoundImage(Bitmap source) {
        if (source==null){
            return null;
        }
        int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(length / 2, length / 2, length / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }
}
